<?php

namespace modules\share_user\controller;

use OpenApi\Attributes as OA;

#[OA\Tag(name: '绑定上下关系', description: '绑定上下关系接口')]
class ApiController extends \core\ApiController
{
    protected $need_login = true;
    protected $model = '\modules\share_user\model\ShareUserModel';
    /**
     * 列表 
     */
    #[OA\Post(path: '/share_user/api/index', summary: '列表', tags: ['绑定上下关系'], parameters: [
        new OA\Parameter(name: 'level', description: '等级', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
    ])]
    public function actionIndex()
    {
        $level = $this->post_data['level'] ?: 1;
        $where['parent_id'] = $this->uid;
        $where['ORDER'] = [
            'id' => 'DESC'
        ];
        $all = $this->model->pager($where);

        foreach ($all['data'] as &$row) {
            $user = get_user($row['user_id']);
            $parent_user = get_user($row['parent_id']);
            $row['user_name'] = \lib\DataMasker::phone($user['phone']);
            $row['parent_name'] = \lib\DataMasker::phone($parent_user['phone']);
            $row['avatar'] = $user['avatar']?:cdn().'/misc/img/avatar.png'; 

        }
        json($all);
    }
    /**
     * 绑定 
     */
    #[OA\Post(path: '/share_user/api/bind', summary: '绑定', tags: ['绑定上下关系'], parameters: [
        new OA\Parameter(name: 'parent_user_id', description: '上级用户ID', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
    ])]
    public function actionBind()
    {
        $parent_user_id = $this->post_data['parent_user_id'];
        if (!$parent_user_id || $parent_user_id == $this->uid) {
            json_error(['msg' => lang('请求异常')]);
        }
        $user = get_user($parent_user_id);
        if (!$user) {
            json_error(['msg' => lang('用户不存在')]);
        }
        $key = 'share_user_lock_' . $parent_user_id . '_' . $this->uid;

        lock_call($key, function () use ($parent_user_id) {
            $res = $this->model->findOne([
                'user_id' => $this->uid,
            ]);
            if ($res) {
                json_error(['msg' => lang('用户已绑定')]);
            }
            $this->model->insert([
                'user_id' => $this->uid,
                'parent_id' => $parent_user_id,
                'created_at' => time(),
            ]);
        }, 1);

        json_success(['msg' => lang('绑定成功')]);
    }
}
